var app = getApp()
//引入请求封装
import {
    request
} from "../../request/request.js"; //ES6 promise
// 引入SDK核心类
// var QQMapWX = require('/utils/qqmap-wx-jssdk');
var QQMapWX = require('../../utils/qqmap-wx-jssdk')
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: 'XCNBZ-UOS3G-XRIQL-ICAKK-JZIOK-EUB27' // 必填
});
Page({
    data: {
        // 图片路径
        img: '/image/',
        longitude: "",
        latitude: "",
        // 当前步骤
        num: 0,
        // 当前出行方式
        way: 'walking',
        // 当前步骤
        nowStep: {},
        // 弹框显示
        show: false,
        // 放弃按钮
        drop: true,
        // 起始点
        from: {
            latitude: '',
            longitude: ''
        },
        to: {
            latitude: '',
            longitude: ''
        },
        // 步骤
        step: [],
        marker: [],
    },
    Data: {
        token: '', //用户token
        id: '' //任务id
    },
    Data2: {
        token: '',
        taskid: '',
        stepNum: '',
        tip: 0
    },
    onLoad(e) {
        let that = this
        wx.getStorage({
            key: 'token',
            success(res) {
                that.Data.token = res.data
                that.Data2.token = res.data
                that.Data.id = e.id
                that.Data2.taskid = e.id
                // 获取步骤
                that.getStep(e.id)
            }
        })
        // 1.判断用户是否打开定位，获取用户当前位置
        this.getLocation()
    },
    // 获取步骤
    async getStep(e) {
        let that = this
        const res = await request({
            url: "/getStep?id=" + e,
            data: that.Data,
            method: "get"
        })
        console.log(res)
        if (res.tips == 'success') {
            that.setData({
                step: res.step
            })
        }
    },
    // 获取用户当前位置
    getLocation() {
        let that = this
        wx.getLocation({
            type: 'gcj02',
            success(res) {
                let from = {
                    latitude: res.latitude,
                    longitude: res.longitude,
                }
                // 拿到数据后设置起始地点的经纬度用于路线绘制
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    from: from,
                    show: true
                })
                // 2.设置导航终点
                that.changeToAddress(0)
            },
            // 如果用户未开启定位，则提示用户，并重复调用该函数
            fail() {
                wx.showToast({
                    icon: 'none',
                    title: '请开启手机定位',
                })
                that.getLocation()
            }
        })
    },
    // 点击上一步
    upToAddress() {
        let num = this.data.num
        if (num == 0)
            return
        else {
            this.setData({
                num: num - 1
            })
            this.changeToAddress(num - 1)
        }
        this.getNext()
    },
    // 点击下一步
    nextToAddress() {
        let that = this
        let num = this.data.num
        if (num >= this.data.step.length - 1) {
            this.setData({
                num: num + 1
            })
            wx.hideLoading({
                success: (res) => {
                    wx.showToast({
                        title: '已完成',
                        icon: 'success',
                    })
                }
            })
            setTimeout(function () {
                wx.redirectTo({
                    url: '../task/task',
                })
                that.getNext()
            }, 1500)
        } else {
            this.setData({
                num: num + 1
            })
            console.log(num + 1)
            this.changeToAddress(num + 1)
        }
        this.getNext()
    },
    async getNext() {
        let that = this
        this.Data2.stepNum = this.data.num
        const res = await request({
            url: "/modifiyStepNum",
            data: that.Data2,
            method: "get"
        })
        console.log(res)
    },
    // 获取导航终点
    // 参数为当前步骤序号，然后找到对应的对应步骤，将步骤地点的经纬度作为导航终点
    changeToAddress(num) {
        // 根据拿到的步骤号获取对应步骤
        let latitude = this.data.step[num].infor[0].latitude
        let longitude = this.data.step[num].infor[0].longitude
        let address = {
            latitude: latitude,
            longitude: longitude
        }
        // 拿到步骤地点经纬度后赋值给marker数值，用于显示定位图标
        let marker = [{
            id: 1,
            latitude: latitude,
            longitude: longitude,
            iconPath: '/image/location.png',
            width: '50px',
            height: '50px'
        }]
        // 将拿到的步骤地点经纬度赋值为终点坐标，用于绘制路线
        // 将原有的“当前步骤号”加一处理
        this.setData({
            nowStep: this.data.step[num].infor[0],
            to: address,
            marker: marker
        })
        // 所有参数准备完成，调用绘制路线函数
        this.drawLine()
    },
    // 用户改变出行方式
    changeWay(e) {
        let way = e.currentTarget.dataset.way
        // 获取用户选择的出行方式,
        this.setData({
            way: way
        })
        // 拿到参数绘制地图
        this.drawLine()
    },
    // 绘制路线
    drawLine(e) {
        var _this = this;
        console.log(this.data.from)
        console.log(this.data.to)
        //调用距离计算接口
        qqmapsdk.direction({
            mode: this.data.way, //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
            //from参数不填默认当前地址
            from: this.data.from,
            to: this.data.to,
            success: function (res) {
                var ret = res;
                var coors = ret.result.routes[0].polyline,
                    pl = [];
                //坐标解压（返回的点串坐标，通过前向差分进行压缩）
                var kr = 1000000;
                for (var i = 2; i < coors.length; i++) {
                    coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
                }
                //将解压后的坐标放入点串数组pl中
                for (var i = 0; i < coors.length; i += 2) {
                    pl.push({
                        latitude: coors[i],
                        longitude: coors[i + 1]
                    })
                }
                //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
                _this.setData({
                    latitude: pl[0].latitude,
                    longitude: pl[0].longitude,
                    polyline: [{
                        points: pl,
                        color: '#FF0000DD',
                        width: 5
                    }]
                })
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            }
        });
    },
    // 处理导航
    navigation() {
        console.log(1)
        let that = this
        wx.openLocation({
            latitude: (Number)(that.data.nowStep.latitude),
            longitude: (Number)(that.data.nowStep.longitude),
            scale: 14, // 缩放比例
            name: that.data.nowStep.stepName,
            address: that.data.nowStep.addressName,
            success: function (r) {
                console.log(r)
            },
            fail(err) {
                console.log(err)
            }
        })
    },
    // 弹窗设置
    changeShow() {
        let show = this.data.show
        this.setData({
            show: !show
        })
    },
    // 拨打电话
    callIphone(e) {
        wx.makePhoneCall({
            phoneNumber: '17319633177',
        })
    },
    // 放弃任务
    drop() {
        let that = this
        wx.showModal({
            title: '放弃任务将不会得到任何赏金，是否继续放弃',
            fail() {

            },
            success() {
                that.cancel()
            }
        })
    },
    async cancel() {
        let that = this
        const res = await request({
            url: "/cancelTask?id=",
            data: that.Data,
            method: "get"
        })
        console.log(res)
        if (res.tips == "success delete") {
            wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000,
                success() {
                    wx.redirectTo({
                        url: '../task/task',
                    })
                }
            })
        }
    }
})